package com.bw.gmall.realtime.dws.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.bean.UserRegisterBean;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.function.DorisMapFunction;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;

/**
 * @Author sw
 * @CreateTime 2024-11-20
 * 12.5 用户域用户注册各窗口汇总表
 */
public class DwsUserUserRegisterWindow extends BaseApp {
    public static void main(String[] args) {
        new DwsUserUserRegisterWindow().start(10025,4,
                Constant.DWS_USER_USER_REGISTER_WINDOW,
                Constant.TOPIC_DWD_USER_REGISTER);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        SingleOutputStreamOperator<UserRegisterBean> result = getResult(dataStreamSource);
        //写到Doris
        result.map(new DorisMapFunction<>())
                .sinkTo(FlinkSinkUtil.getDorisSink("dws_user_user_register_window"));
    }

    private static SingleOutputStreamOperator<UserRegisterBean> getResult(DataStreamSource<String> dataStreamSource) {
         return dataStreamSource.map(JSON::parseObject)
                .assignTimestampsAndWatermarks(WatermarkStrategy
                        .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((event, timestamp) -> event.getLong("create_time"))
                        .withIdleness(Duration.ofSeconds(120)))
                .windowAll(TumblingEventTimeWindows.of(Time.seconds(3)))
                .aggregate(new AggregateFunction<JSONObject, Long, Long>() {
                               /**
                                * 初始化累加器，按钮名称为空字符串，次数初始化为0
                                *
                                * @return
                                */
                               @Override
                               public Long createAccumulator() {
                                   return 0L;
                               }

                               /**
                                * 更新按钮名称（其实这里可以保持不变，只是示例完整写法）和点击次数（每次加1）
                                *
                                * @param jsonObject
                                * @param aLong
                                * @return
                                */
                               @Override
                               public Long add(JSONObject jsonObject, Long aLong) {
                                   return aLong + 1;
                               }

                               /**
                                * 返回最终结果，包含按钮名称和点击次数
                                *
                                * @param aLong
                                * @return
                                */
                               @Override
                               public Long getResult(Long aLong) {
                                   return aLong;
                               }

                               /**
                                * 合并不同分区的结果，将点击次数相加
                                *
                                * @param aLong
                                * @param acc1
                                * @return
                                */
                               @Override
                               public Long merge(Long aLong, Long acc1) {
                                   return aLong + acc1;
                               }
                           },
                        new ProcessAllWindowFunction<Long, UserRegisterBean, TimeWindow>() {
                            @Override
                            public void process(ProcessAllWindowFunction<Long, UserRegisterBean, TimeWindow>.Context context, Iterable<Long> iterable, Collector<UserRegisterBean> collector) throws Exception {
                                Long next = iterable.iterator().next();
                                collector.collect(new UserRegisterBean(DateFormatUtil.tsToDateTime(context.window().getStart()),
                                        DateFormatUtil.tsToDateTime(context.window().getEnd()),
                                        DateFormatUtil.tsToDate(System.currentTimeMillis()),
                                        next));
                            }
                        });
    }
}
